package com.uinnova.product.eam.service.impl;

import com.binary.core.lang.StringUtils;
import com.binary.core.util.BinaryUtils;
import com.binary.jdbc.Page;
import com.uinnova.product.eam.comm.model.es.ArchReview;
import com.uinnova.product.eam.constant.ArchReviewState;
import com.uinnova.product.eam.model.cj.domain.*;
import com.uinnova.product.eam.model.cj.enums.QuestionCheckEnum;
import com.uinnova.product.eam.model.cj.enums.QuestionStatusEnum;
import com.uinnova.product.eam.model.cj.request.PlanChapterQuestionRequest;
import com.uinnova.product.eam.model.cj.vo.PlanChapterQuestionVO;
import com.uinnova.product.eam.model.cj.vo.QuestionAnswerVO;
import com.uinnova.product.eam.model.constants.Constants;
import com.uinnova.product.eam.model.es.PlanProcessRelation;
import com.uinnova.product.eam.service.ArchReviewService;
import com.uinnova.product.eam.service.GTPlanChapterQuestionService;
import com.uinnova.product.eam.service.PlanProcessRelationService;
import com.uinnova.product.eam.service.cj.dao.ArchReviewDao;
import com.uinnova.product.eam.service.cj.dao.ChapterContextDao;
import com.uinnova.product.eam.service.cj.dao.PlanChapterQuestionDao;
import com.uinnova.product.eam.service.cj.service.PlanChapterInstanceService;
import com.uinnova.product.eam.service.cj.service.PlanDesignInstanceService;
import com.uinnova.product.eam.service.exception.BusinessException;
import com.uinnova.product.eam.vo.ArchReviewRes;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.query.CSysUser;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: Lc
 * @create: 2022-03-01 19:53
 */
@Service
@Log4j2
public class GTPlanChapterQuestionServiceImpl implements GTPlanChapterQuestionService {

    @Resource
    private PlanChapterQuestionDao planChapterQuestionDao;

    @Resource
    private PlanChapterInstanceService planChapterInstanceService;
    @Resource
    private IUserApiSvc userApiSvc;

    @Resource
    @Lazy
    private PlanDesignInstanceService planDesignInstanceService;
    @Autowired
    private ArchReviewDao archReviewDao;

    @Autowired
    private ChapterContextDao chapterContextDao;
    @Resource
    private ArchReviewService archReviewService;
    @Resource
    private PlanProcessRelationService planProcessRelationService;

    @Override
    public Page<PlanChapterQuestionVO> findGTQuestionList(PlanChapterQuestionRequest request) {
        if (request == null) {
            throw new BusinessException("请求参数不能为空!");
        }
        if (StringUtils.isBlank(request.getBusinessKey()) && request.getArchReviewId() == null) {
            throw new BusinessException("缺少参数");
        }
        ArchReview archReview;
        if (!StringUtils.isBlank(request.getBusinessKey())) {
            archReview = archReviewDao.getById(Long.valueOf(request.getBusinessKey()));
        } else {
            archReview = archReviewDao.getById(request.getArchReviewId());
        }
        String processInstanceId = "-";
        if (!StringUtils.isBlank(archReview.getProcessInstanceId())) {
            processInstanceId = archReview.getProcessInstanceId();
        }
        Assert.notNull(archReview, "未找到架构评审提交记录");

        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        // 250402 新增需求 如果是已完结的流程，评审结果为“同意” 需要查询方案设计资产相应版本对应的问题列表
        // 250402.1 查询流程状态 根据流程状态判断是否已完结
        ArchReviewRes archReviewRes = archReviewService.getState(processInstanceId);
        // 250402.2 如果是已完结的流程，评审结果为“同意” 根据流程id查询对应版本的方案id
        List<Long> planIds = archReview.getPlanIds();
        if (ArchReviewState.PASS.equals(archReviewRes.getState())) {
            List<PlanProcessRelation> planProcessRelations = planProcessRelationService.getByProcessInstanceId(processInstanceId);
            if (!BinaryUtils.isEmpty(planProcessRelations)) {
                planIds = planProcessRelations.stream().map(PlanProcessRelation::getPlanId).collect(Collectors.toList());
            }
        }
        queryBuilder.must(QueryBuilders.termsQuery("planId", planIds));
        queryBuilder.must(QueryBuilders.termQuery("processInstanceId.keyword", processInstanceId));
        if (!StringUtils.isEmpty(request.getQuestion())) {
            queryBuilder.must(QueryBuilders.wildcardQuery("question.keyword", "*" + request.getQuestion() + "*"));
        }
        //国投：任何人可以看所有问题
        // 判断当前登录人是否是提交人，提交人查询所有问题，审批人只查询自己的问题
//        if (!Objects.equals(archReview.getCreatorCode(), SysUtil.getCurrentUserInfo().getLoginCode())) {
//            if (StringUtils.isEmpty(request.getProcessInstanceId())) {
//                throw new BusinessException("流程实例不能为空!");
//            }
//            if (StringUtils.isEmpty(request.getTaskDefinitionKey())) {
//                throw new BusinessException("任务定义不能为空!");
//            }
//            queryBuilder.must(QueryBuilders.termQuery("creator.keyword", SysUtil.getCurrentUserInfo().getLoginCode()));
//            queryBuilder.must(QueryBuilders.termQuery("processInstanceId.keyword", request.getProcessInstanceId()));
//            queryBuilder.must(QueryBuilders.termQuery("taskDefinitionKey.keyword", request.getTaskDefinitionKey()));
//        }
        Page<PlanChapterQuestion> questionPage = planChapterQuestionDao.getSortListByQuery(request.getPageNum(), request.getPageSize(), queryBuilder, "createTime", false);
        List<PlanChapterQuestionVO> questionVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(questionPage.getData())) {
            Map<Long, PlanDesignInstance> planMap = new HashMap<>();
            List<PlanDesignInstance> plans = planDesignInstanceService.getByIds(planIds);
            if (!CollectionUtils.isEmpty(plans)) {
                planMap = plans.stream().collect(Collectors.toMap(PlanDesignInstance::getId, Function.identity()));
            }
            Set<String> creatorLoginCodes = questionPage.getData().stream().map(PlanChapterQuestion::getCreator).collect(Collectors.toSet());
            CSysUser cdt = new CSysUser();
            cdt.setLoginCodes(creatorLoginCodes.toArray(new String[creatorLoginCodes.size()]));
            List<SysUser> sysUsers = userApiSvc.getSysUserByCdt(cdt);
            Map<String, SysUser> userMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(sysUsers)) {
                userMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getLoginCode, Function.identity()));
            }
            for (PlanChapterQuestion question : questionPage.getData()) {
                PlanChapterQuestionVO questionVo = new PlanChapterQuestionVO();
                questionVo.setId(question.getId());
                questionVo.setQuestion(question.getQuestion());
                questionVo.setCreator(question.getCreator());
                questionVo.setCreatorName(userMap.containsKey(question.getCreator()) ? userMap.get(question.getCreator()).getUserName() : "-");
                questionVo.setPlanName(planMap.containsKey(question.getPlanId()) ? planMap.get(question.getPlanId()).getName() : "-");
                questionVo.setPlanId(question.getPlanId());
                questionVo.setPlanChapterId(question.getPlanChapterId());
                questionVo.setPlanChapterContextId(question.getPlanChapterContextId());
                questionVo.setAnnotationId(question.getAnnotationId());
                // 问题回复内容
                if (!CollectionUtils.isEmpty(question.getAnswerList())) {
                    List<QuestionAnswerVO> answerList = question.getAnswerList();
                    questionVo.setAnswer(answerList.get(answerList.size() - 1).getAnswer());
                } else {
                    questionVo.setAnswer(Constants.CENTRE_LINE);
                }
                // 回复状态
                questionVo.setQuestionState(QuestionStatusEnum.getQuestionDesc(question.getQuestionState()));
                // 验证功能是否可用
                if (Objects.equals(question.getQuestionState(), QuestionStatusEnum.NOT_RECTIFIED.getState()) && Objects.equals(question.getCheckResult(), QuestionCheckEnum.LATER_CHECK.getCode())) {
                    questionVo.setCheckSign(false);
                } else {
                    questionVo.setCheckSign(true);
                }
                // 验证状态
                questionVo.setCheckResult(QuestionCheckEnum.getCheckDesc(question.getCheckResult()));
                // 章节信息
                if (!BinaryUtils.isEmpty(question.getPlanChapterId())) {
                    ChapterInstance chapterInstance = planChapterInstanceService.getPlanChapterInstance(question.getPlanChapterId());
                    if (chapterInstance != null && !StringUtils.isEmpty(chapterInstance.getName()) && !chapterInstance.getDeleted()) {
                        String moduleName = chapterInstance.getName();
                        ChapterContext context = chapterContextDao.getById(question.getPlanChapterId());
                        if (!BinaryUtils.isEmpty(context)
                                && !CollectionUtils.isEmpty(context.getModuleList())
                                && !BinaryUtils.isEmpty(question.getPlanChapterContextId())) {
                            ContextModule module = context.getModuleList().stream()
                                    .collect(Collectors.toMap(ContextModule::getId, Function.identity()))
                                    .get(question.getPlanChapterContextId());
                            if (module != null) {
                                PlanTemplateChapterData moduleDefinition = module.getModuleDefinition();
                                Integer moduleType = moduleDefinition.getType();
                                // 制品
                                int product = 1;
                                // 表格
                                int table = 2;
                                // 富文本
                                int richText = 3;
                                //清单制品
                                int dataSet = 4;
                                //附件
                                int appendix = 5;
                                if (moduleType == product) {
                                    moduleName = moduleName + Constants.SLASH + moduleDefinition.getProductName();
                                } else if (moduleType == table) {
                                    moduleName = moduleName + Constants.SLASH + moduleDefinition.getDataTableName();
                                } else if (moduleType == richText) {
                                    moduleName = moduleName + Constants.SLASH + moduleDefinition.getRichTextName();
                                } else if (moduleType == dataSet) {
                                    moduleName = moduleName + Constants.SLASH + moduleDefinition.getDataSetName();
                                } else if (moduleType == appendix) {
                                    moduleName = moduleName + Constants.SLASH + moduleDefinition.getAppendixName();
                                }
                            }
                        }
                        questionVo.setModule(moduleName);
                    }
                }
//                // 模板数据内容
//                PlanTemplateChapterData chapterData = planTemplateChapterService.getTemplateChapterData(question.getPlanChapterContextId());
//                if (chapterInstance != null && !StringUtils.isEmpty(chapterInstance.getName())) {
//                    String module = chapterInstance.getName();
//                    if (chapterData != null) {
//                        if (ChapterDataTypeEnum.PRODUCT.getDataType().equals(chapterData.getType())
//                                && !StringUtils.isEmpty(chapterData.getProductName())) {
//                            module = module + Constants.SLASH + chapterData.getProductName();
//                        } else if (ChapterDataTypeEnum.DATA_TABLE.getDataType().equals(chapterData.getType())
//                                && !StringUtils.isEmpty(chapterData.getDataTableName())) {
//                            module = module + Constants.SLASH + chapterData.getDataTableName();
//                        } else if (ChapterDataTypeEnum.RICH_TEXT.getDataType().equals(chapterData.getType())
//                                && !StringUtils.isEmpty(chapterData.getRichTextName())) {
//                            module = module + Constants.SLASH + chapterData.getRichTextName();
//                        }
//                    }
//                    questionVo.setModule(module);
//                }
                questionVoList.add(questionVo);
            }

        }
        // 重新控制分页
        Page<PlanChapterQuestionVO> page = new Page<>();
        page.setPageNum(questionPage.getPageNum());
        page.setPageSize(questionPage.getPageSize());
        page.setTotalPages(questionPage.getTotalPages());
        page.setTotalRows(questionPage.getTotalRows());
        page.setData(questionVoList);
        return page;
    }

}
